package com.pb.metadata.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pb.infra.oth.util.JwtTokenConfig;
import com.pb.metadata.mapper.RunEnvironmentMapper;
import com.pb.infra.oth.entity.common.Page;
import com.pb.infra.oth.entity.common.Result;
import com.pb.infra.oth.util.DBHelper;
import io.jsonwebtoken.Claims;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 运行环境管理
 * @author liaohaoyuan
 * @date 20210301
 */
@Service
public class RunEnvironmentService {

    /**
     * 运行环境表DAO映射对象
     */
    @Resource
    private RunEnvironmentMapper runEnvironmentMapper;

    /**
     * jwttoken配置类
     */
    @Resource
    private JwtTokenConfig jwtTokenConfig;

    /**
     * 查询分页数据
     * @param map 查询参数
     * @param page 页码
     * @return
     */
    public Result select(Map<String, Object> map, Page page){
        if (page != null && page.getPageIndex() != null && page.getPageSize() != null) {
            PageHelper.startPage(page.getPageIndex(), page.getPageSize());
        }
        List<Map<String, Object>> list = runEnvironmentMapper.select(map);
        return Result.ok(new PageInfo(list).getTotal(), list);
    }

    /**
     * 查询分页数据
     * @param map 查询参数
     * @return
     */
    public Result selectEnv(Map<String, Object> map){
        List<Map<String, Object>> list = runEnvironmentMapper.selectEnv(map);
        return Result.ok(new PageInfo(list).getTotal(), list);
    }

    /**
     * 运行环境新建数据
     * @param paramMap 保存数据
     * @return
     */
    public Result insert(Map<String, Object> paramMap, HttpServletRequest request){
        String token = request.getHeader(jwtTokenConfig.getHeader());
        Claims claims = jwtTokenConfig.getClaimByToken(token);
        String userId = (String)claims.get(jwtTokenConfig.getSub());
        paramMap.put("createUser",userId);
        paramMap.put("environmentId", UUID.randomUUID().toString().replace("-", ""));
        paramMap.put("identifyId", UUID.randomUUID().toString().replace("-", ""));
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        paramMap.put("createTime",format.format(new Date()));
        runEnvironmentMapper.insert(paramMap);
        return Result.OK_EMPTY;
     }

    /**
     * 运行环境修改
     * @return
     */
     public  Result update(Map<String, Object> paramMap, HttpServletRequest request){
         String token = request.getHeader(jwtTokenConfig.getHeader());
         Claims claims = jwtTokenConfig.getClaimByToken(token);
         String userId = (String)claims.get(jwtTokenConfig.getSub());
         paramMap.put("updateUser",userId);
         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         paramMap.put("updateTime",format.format(new Date()));
         runEnvironmentMapper.update(paramMap);
         return Result.OK_EMPTY;
     }

    /**
     * 删除运行环境数据
     * @param paramMap
     */
    public void delete(List<String> paramMap) {
        this.runEnvironmentMapper.delete(paramMap);
    }

    /**
     * 启用停用数据库用户
     * @param paramMap
     */
    public void startOrStop( List<Map<String,Object>> paramMap){
        for (Map<String,Object> map:paramMap){
            String str=(String) map.get("activeFlag");
            map.put("activeFlag","1".equals(str)?"0":"1");
            runEnvironmentMapper.startOrStop(map);
        }
    }

    /**
     * 运行环境管理参数配置
     * @param paramMap 保存数据
     * @return
     */
    public Result saveParam(Map<String, Object> paramMap){
        String userNameParam=(String)paramMap.get("userNameParam");
        String passwordParam=(String)paramMap.get("passwordParam");
        Map map=new HashedMap();
        map.put("environmentId",paramMap.get("environmentId"));
        map.put("paramName","USER-NAME");
        map.put("serialNo",1);
        map.put("paramValue",userNameParam);
        runEnvironmentMapper.saveParam(map);
        map.clear();
        map.put("environmentId",paramMap.get("environmentId"));
        map.put("paramName","PASSWORD");
        map.put("serialNo",2);
        map.put("paramValue",passwordParam);
        runEnvironmentMapper.saveParam(map);
        return Result.OK_EMPTY;
    }

    /**
     * 测试数据库连接
     *
     * @param paramMap
     * @return
     */
    public Map<String, Object> connectionCheck(Map<String, Object> paramMap) {
        Map<String, Object> dataMap = new HashMap<>();
        // com.pb.infra.oth.util.Base64 base = new Base64();
        String databaseUrl = paramMap.get("databaseUrl").toString();
        String username = paramMap.get("userNameParam").toString();
        String password = paramMap.get("passwordParam").toString(); //base.getFromBase64(paramMap.get("passwordParam").toString());
        String databaseType = paramMap.get("databaseType").toString();
        Connection conn = null;
        try {
            String jdbcurl = "";
            if ("ORACLE".equals(databaseType)) {
                jdbcurl = "jdbc:oracle:thin:@" + databaseUrl;
                conn = DBHelper.initOracle(jdbcurl,username,password, false);
            } else if ("MYSQL".equals(databaseType)) {
                jdbcurl = "jdbc:mysql://" + databaseUrl;
                conn = DBHelper.initMysql(jdbcurl,username,password, false);
            } else {
                dataMap.put("result", false);
                dataMap.put("msg", "数据库类型错误，当前仅支持MYSQL和ORACLE");
            }
        } catch (Exception e) {
            dataMap.put("result", false);
            dataMap.put("msg", e.getMessage());
            //throw new AppAuthException(ErrorCode.ErrorCodeEnum.ACCESS_USER_INFO);
        }finally {
            if(conn!=null){
                dataMap.put("result",true);
                dataMap.put("msg", "数据库连接成功");
                try {
                    conn.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }else{
                dataMap.put("result", false);
                dataMap.put("msg", "数据库连接失败");
            }
        }
        return dataMap;
    }
}
